package com.AICoupon.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.AICoupon.dto.Result;
import com.AICoupon.entity.ShopType;
import com.AICoupon.mapper.ShopTypeMapper;
import com.AICoupon.service.IShopTypeService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.AICoupon.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    public Result queryTypeList() {
        //1.从redis查询商户类型列表
        List<String> shopTypeList = stringRedisTemplate.opsForList().range(CACHE_SHOP_TYPE_KEY, 0, -1);
        //2.如果存在，返回
        if (shopTypeList != null && !shopTypeList.isEmpty()) {
            // 将字符串列表转换为ShopType对象列表
            List<ShopType> typeList = shopTypeList.stream()
                .map(item -> JSONUtil.toBean(item, ShopType.class))
                .collect(java.util.stream.Collectors.toList());
            return Result.ok(typeList);
        }
        //3.不存在，查询数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();
        //4.数据库不存在，返回错误
        if (typeList == null || typeList.isEmpty()) {
            return Result.fail("商户类型不存在");
        }
        //5.数据库存在，写入redis
        // 将ShopType对象转换为JSON字符串并存入Redis List
        for (ShopType type : typeList) {
            stringRedisTemplate.opsForList().rightPush(CACHE_SHOP_TYPE_KEY, JSONUtil.toJsonStr(type));
        }
        // 设置过期时间
        stringRedisTemplate.expire(CACHE_SHOP_TYPE_KEY, CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);
        //6.返回
        return Result.ok(typeList);
    }
}
